<template>
  <div class="hours-management">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="志愿者">
          <el-input v-model="searchForm.volunteer" placeholder="请输入志愿者姓名" />
        </el-form-item>
        <el-form-item label="项目">
          <el-select v-model="searchForm.project" placeholder="请选择项目">
            <el-option label="全部项目" value="" />
            <el-option v-for="item in projects" :key="item.id" :label="item.title" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>服务时长记录</span>
          <el-button type="primary" @click="handleExport">导出数据</el-button>
        </div>
      </template>
      
      <el-table :data="hoursList" border stripe v-loading="loading" element-loading-text="加载中...">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="volunteerName" label="志愿者">
          <template #default="{ row }">
            {{ row.volunteerName || '未知志愿者' }}
          </template>
        </el-table-column>
        <el-table-column prop="activityTitle" label="项目名称">
          <template #default="{ row }">
            {{ row.activityTitle || '独立服务' }}
          </template>
        </el-table-column>
        <el-table-column prop="serviceHours" label="服务时长" width="100">
          <template #default="{ row }">
            {{ row.serviceHours }} 小时
          </template>
        </el-table-column>
        <el-table-column prop="serviceDate" label="服务日期" width="180">
          <template #default="{ row }">
            {{ formatDate(row.serviceDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="serviceLocation" label="服务地点" width="150" />
        <el-table-column prop="createTime" label="记录时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="row.status === 0 || row.status === 'pending'"
              link 
              type="primary" 
              @click="handleApprove(row)"
            >通过</el-button>
            <el-button 
              v-if="row.status === 0 || row.status === 'pending'"
              link 
              type="danger" 
              @click="handleReject(row)"
            >拒绝</el-button>
            <el-button link type="primary" @click="handleDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="服务时长详情"
      width="600px"
    >
      <div v-loading="detailLoading" element-loading-text="加载中...">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="志愿者">{{ currentDetail.volunteerName || '未知志愿者' }}</el-descriptions-item>
          <el-descriptions-item label="项目名称">{{ currentDetail.activityTitle || '独立服务' }}</el-descriptions-item>
          <el-descriptions-item label="服务时长">{{ currentDetail.serviceHours }} 小时</el-descriptions-item>
          <el-descriptions-item label="服务日期">{{ formatDate(currentDetail.serviceDate) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentDetail.status)">
              {{ getStatusText(currentDetail.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="服务地点">{{ currentDetail.serviceLocation || '暂无' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">{{ formatDate(currentDetail.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="服务内容" :span="2">{{ currentDetail.description || '暂无' }}</el-descriptions-item>
          <el-descriptions-item v-if="currentDetail.rejectReason" label="拒绝原因" :span="2">{{ currentDetail.rejectReason }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getServiceHoursList,
  getServiceHourDetail,
  approveServiceHour,
  rejectServiceHour,
  exportServiceHours,
  getProjectOptions
} from '@/api/hours'

// 搜索表单
const searchForm = reactive({
  volunteer: '',
  project: '',
  status: '',
  dateRange: []
})

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 项目列表
const projects = ref([])
const loading = ref(false)

// 时长记录列表
const hoursList = ref([])

// 详情对话框
const detailDialogVisible = ref(false)
const currentDetail = ref({})
const detailLoading = ref(false)

// 初始化加载数据
onMounted(() => {
  loadProjects()
  loadHoursList()
})

// 加载项目选项
const loadProjects = async () => {
  try {
    const res = await getProjectOptions()
    if (res && res.code === 200) {
      projects.value = res.data || []
    }
  } catch (error) {
    console.error('加载项目选项失败:', error)
  }
}

// 加载时长记录列表
const loadHoursList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      volunteerName: searchForm.volunteer || undefined,
      activityId: searchForm.project || undefined,
      status: searchForm.status === '' ? undefined : searchForm.status,
      startDate: searchForm.dateRange && searchForm.dateRange[0] ? searchForm.dateRange[0] : undefined,
      endDate: searchForm.dateRange && searchForm.dateRange[1] ? searchForm.dateRange[1] : undefined
    }
    
    const res = await getServiceHoursList(params)
    if (res && res.code === 200) {
      hoursList.value = res.data.list || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res?.message || '获取服务时长记录失败')
    }
  } catch (error) {
    console.error('加载服务时长记录出错:', error)
    ElMessage.error('获取服务时长记录失败')
  } finally {
    loading.value = false
  }
}

// 日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return '暂无';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-');
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    0: 'warning',    // 待审核
    1: 'success',    // 已通过
    2: 'danger',     // 已拒绝
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '待审核',
    1: '已通过',
    2: '已拒绝',
    'pending': '待审核',
    'approved': '已通过',
    'rejected': '已拒绝'
  }
  return texts[status] || '未知'
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  loadHoursList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'dateRange' ? [] : ''
  })
  currentPage.value = 1
  loadHoursList()
}

// 处理导出
const handleExport = async () => {
  try {
    const params = {
      volunteerName: searchForm.volunteer || undefined,
      activityId: searchForm.project || undefined,
      status: searchForm.status === '' ? undefined : searchForm.status,
      startDate: searchForm.dateRange && searchForm.dateRange[0] ? searchForm.dateRange[0] : undefined,
      endDate: searchForm.dateRange && searchForm.dateRange[1] ? searchForm.dateRange[1] : undefined
    }
    
    // 显示加载中状态
    const loading = ElMessage({
      message: '导出数据中，请稍候...',
      type: 'info',
      duration: 0
    })
    
    try {
      // 调用导出API
      const response = await exportServiceHours(params)
      
      // 从Content-Disposition头获取文件名（如果有）
      let filename = '服务时长记录.xlsx'
      const contentDisposition = response.headers['content-disposition']
      if (contentDisposition) {
        const filenameMatch = contentDisposition.match(/filename=(.+)/)
        if (filenameMatch && filenameMatch[1]) {
          // 去除引号并解码
          filename = filenameMatch[1].replace(/"/g, '').replace(/'/g, '')
        }
      }
      
      // 创建Blob对象
      const contentType = response.headers['content-type']
      const blob = new Blob([response.data], { type: contentType })
      
      // 创建下载链接
      const downloadLink = document.createElement('a')
      const url = window.URL.createObjectURL(blob)
      
      // 设置下载属性
      downloadLink.href = url
      downloadLink.download = filename
      downloadLink.style.display = 'none'
      
      // 添加到文档并触发点击
      document.body.appendChild(downloadLink)
      downloadLink.click()
      
      // 清理
      document.body.removeChild(downloadLink)
      window.URL.revokeObjectURL(url)
      
      ElMessage.success('导出成功')
    } finally {
      // 确保关闭加载提示
      loading.close()
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error(`导出失败: ${error.message || '未知错误'}`)
  }
}

// 处理审核通过
const handleApprove = (row) => {
  ElMessageBox.confirm(
    '确认通过该时长记录？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await approveServiceHour(row.id)
      if (res && res.code === 200) {
        ElMessage.success('审核通过成功')
        loadHoursList() // 重新加载数据
      } else {
        ElMessage.error(res?.message || '审核操作失败')
      }
    } catch (error) {
      console.error('审核通过出错:', error)
      ElMessage.error('审核操作失败，请重试')
    }
  }).catch(() => {})
}

// 处理审核拒绝
const handleReject = (row) => {
  ElMessageBox.prompt('请输入拒绝原因', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'textarea',
    inputPlaceholder: '请输入拒绝原因'
  }).then(async ({ value }) => {
    try {
      const res = await rejectServiceHour(row.id, value)
      if (res && res.code === 200) {
        ElMessage.success('已拒绝该记录')
        loadHoursList() // 重新加载数据
      } else {
        ElMessage.error(res?.message || '拒绝操作失败')
      }
    } catch (error) {
      console.error('拒绝操作出错:', error)
      ElMessage.error('拒绝操作失败，请重试')
    }
  }).catch(() => {})
}

// 查看详情
const handleDetail = async (row) => {
  detailDialogVisible.value = true
  detailLoading.value = true
  currentDetail.value = {} // 清空之前的数据
  
  try {
    const res = await getServiceHourDetail(row.id)
    if (res && res.code === 200) {
      currentDetail.value = res.data
    } else {
      ElMessage.error(res?.message || '获取详情失败')
    }
  } catch (error) {
    console.error('获取详情出错:', error)
    ElMessage.error('获取详情失败')
  } finally {
    detailLoading.value = false
  }
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  loadHoursList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadHoursList()
}
</script>

<style scoped lang="scss">
.hours-management {
  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 